package com.kfm.controller;

import com.kfm.commons.AjaxResult;
import com.kfm.config.FileConfig;
import com.kfm.entity.Directory;
import com.kfm.entity.User;
import com.kfm.service.DirectoryService;
import com.kfm.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;

@RestController
@RequestMapping("/directory")
@CrossOrigin("*")
public class DirectoryController {

    @Resource
    UserService userService;

    @Resource
    DirectoryService directoryService;

    @PostMapping("/newDir")
    public AjaxResult newDir(Integer userId, String dirName) {
        User user = userService.selectByPrimaryKey(userId);
        String path = FileConfig.getLocalPath() + File.separator + user.getUsername() + File.separator + dirName;
        File file = new File(path);
        if (file.isDirectory() || !file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (mkdirs) {
                Directory directory = new Directory();
                directory.setDirectoryName(dirName);
                Directory directory1 = directoryService.selectByDirName(user.getUsername());
                directory.setParentId(directory1.getId());
                int i = directoryService.insertSelective(directory);
                return i > 0 ? AjaxResult.success("创建成功") : AjaxResult.fail("创建失败");
            } else {
                return AjaxResult.fail("创建失败");
            }
        }
        return AjaxResult.fail("目录已经存在");
    }
}
